//
//  XSVideoEditeViewController.m
//  AudioVideo
//
//  Created by xueshan1 on 2019/8/22.
//  Copyright © 2019 xueshan1. All rights reserved.
//

#import "XSVideoEditeViewController.h"
#import "XSVideoToolBarView.h"

@interface XSVideoEditeViewController ()
{
    BOOL _needWatermask;
    BOOL _needAddCustomAudio;
    BOOL _needRemoveOriginAudio;
}

//UI
@property (weak, nonatomic) IBOutlet UIButton *backBtn;

@property(nonatomic,strong)XSVideoToolBarView *toolBarView;
@property(nonatomic,strong)XSVideoWaterPrintEditeView *waterEditView;
@property(nonatomic,strong)IBOutlet UIView *waterView;
//audio
@property(nonatomic,strong)XSAudioListView *audioListView;
@property(nonatomic,strong)NSURL *audioURL;
@property(nonatomic,strong)AVAudioPlayer *audioPlayer;


@end


@implementation XSVideoEditeViewController

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    
    [[XSAVPlayer shareInstance]sf_deallocPlayer];
    [self.audioPlayer stop];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [self.safeView addSubview:self.toolBarView];

    if (self.avasset) {
        
        [[XSAVPlayer shareInstance]playVideoWithAVAsset:self.avasset onPlayView:self.view belowView:self.safeView];
        
    } else if (self.videoURL ) {
        self.avasset = [AVAsset assetWithURL:self.videoURL];

        [[XSAVPlayer shareInstance]playVideoWithAVAsset:self.avasset onPlayView:self.view belowView:self.safeView];

     }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    

}
 
- (void)setupUI{

    [self.safeView sendSubviewToBack:self.waterView];

}

- (XSVideoToolBarView *)toolBarView{
    if (!_toolBarView) {
        _toolBarView = [[XSVideoToolBarView alloc]initWithFrame:CGRectMake(0, 40, kWidth, 80)];
        _toolBarView.backgroundColor = [UIColor clearColor];
        WeakSelf
        _toolBarView.clickBackBtnBlock = ^{
            [weakSelf backAction:nil];
        };
        _toolBarView.clickaudioBtnBlock = ^{
            [weakSelf addAudio:nil];
        };
        _toolBarView.clickwatermaskBtnBlock = ^{
            [weakSelf imageWater:nil];
        };
        _toolBarView.clicksaveBtnBlock = ^{
            [weakSelf systhesizeFinalVideo:nil];
        };
        
        
    }
    return _toolBarView;
}

#pragma mark - 最终合成
- (IBAction)systhesizeFinalVideo:(id)sender {
   //2.水印
    UIImage *waterImage = nil;
    if (self.waterView.subviews.count > 0) {
        _needWatermask = YES;
        for (UIView *view in self.waterView.subviews) {
            if ([view isKindOfClass:[XSVideoWaterPrintView class]]) {
                [(XSVideoWaterPrintView *)view setHightlight:NO];
            }
        }
        waterImage = [self.waterView toImage];
        
    }else{
        _needWatermask = NO;
        NSLog(@"不需要加水印");
    }
 
     //3.音频
    if (_needAddCustomAudio) {
        [self.audioListView hiddenListView];
    }else{
        NSLog(@"不需要+音频");
    }
    
    if (!_needWatermask && !_needAddCustomAudio) {
//        [self.navigationController popToRootViewControllerAnimated:YES];
        MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        hud.label.text = @"已经保存";
        [hud hideAnimated:YES afterDelay:1.2];
        return;
    }
    
    //
    [XSAVTools systhesizeVideoWithOriginURL:self.videoURL orAsset:self.avasset addCustomAudio:self.audioURL waterImage:waterImage exportPath:[XSFileManager tempVideoPath]  completionHandler:^(int status, NSString *errorMsg, NSURL *exportURL) {
        if (errorMsg == nil) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }];
    
    
}



#pragma mark - 音频
- (XSAudioListView *)audioListView{
    if (!_audioListView) {
        _audioListView = [[XSAudioListView alloc]initWithFrame:CGRectMake(0, kHeight, kWidth, 150)];
        _audioListView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview: _audioListView];
        WeakSelf
        _audioListView.selectedAudioBlock = ^(NSString * _Nonnull path) {
            if (IS_NSString(path)) {
                weakSelf.audioURL = [NSURL fileURLWithPath:path];
                self->_needAddCustomAudio = YES;
 
                weakSelf.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:weakSelf.audioURL error:nil];
                weakSelf.audioPlayer.numberOfLoops = 999;
                [weakSelf.audioPlayer play];
            }else{
                [weakSelf.audioPlayer pause];
                weakSelf.audioPlayer = nil;
                weakSelf.audioURL = nil;
                self->_needAddCustomAudio = NO;
            }
            
        };
        
        
        
    }
    return _audioListView;
}
//消音
- (IBAction)removeAudio:(id)sender {
    _needRemoveOriginAudio = YES;
 
}
//添加音频
- (IBAction)addAudio:(id)sender {
    [self.audioListView showAudioListView];
}

#pragma mark - 水印
- (IBAction)imageWater:(id)sender {
    [self.view addSubview:self.waterEditView];
    [self.waterEditView appear];
    
}

- (XSVideoWaterPrintEditeView *)waterEditView{
    if (!_waterEditView) {
        _waterEditView = [[XSVideoWaterPrintEditeView alloc]initWithFrame:self.view.bounds];
        WeakSelf
        _waterEditView.confirmEditBlock = ^(NSString *str,UIColor *waterColor) {
            if (str.length) {
                //创建一个水印
                CGFloat hei = [str getSizeWithFontSize:WaterLabFont maxWidth:200].height;
                XSVideoWaterPrintView *waterPrint = [[XSVideoWaterPrintView alloc]initWithFrame:CGRectMake(0, 0, 200, hei + 10)];
                waterPrint.center = weakSelf.waterView.center;
                waterPrint.textColor = waterColor;
                waterPrint.text = str;
                weakSelf.waterView.hidden = NO;
                [weakSelf.waterView  insertSubview:waterPrint atIndex:0];
                
            }
            
        };
        _waterEditView.cancelEditBlock = ^{
            
        };
        _waterEditView.selectImageFinishBlock = ^(UIImage *waterImage) {
            if (waterImage) {
                //创建一个水印
                XSVideoWaterPrintView *waterPrint = [[XSVideoWaterPrintView alloc]initWithFrame:CGRectMake(0, 0, waterImage.size.width + 20, waterImage.size.height + 20) waterType:VideoWaterPrintType_Image];
                waterPrint.center = weakSelf.waterView.center;
                waterPrint.textColor = [UIColor lightGrayColor];
                waterPrint.waterImage = waterImage;
                weakSelf.waterView.hidden = NO;
                [weakSelf.waterView  insertSubview:waterPrint atIndex:0];
                
            }
        };
    }
    return _waterEditView;
}



//合并
- (void)mergeFinalVideo{
    AVAsset *videoAsset = [AVAsset assetWithURL:self.videoURL];
    CMTimeRange video_timeRange = CMTimeRangeMake(kCMTimeZero, videoAsset.duration);
    //获取原视频的 视频轨
    AVAssetTrack *videoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo]objectAtIndex:0];
    
    AVMutableComposition *composition = [[AVMutableComposition alloc]init];
    //video
    AVMutableCompositionTrack *compositionVideoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    [compositionVideoTrack insertTimeRange:video_timeRange ofTrack:videoTrack atTime:kCMTimeZero error:nil];
    compositionVideoTrack.preferredTransform = videoTrack.preferredTransform;

    //是否加入视频原声
    AVMutableCompositionTrack *originalAudioCompositionTrack = nil;
    if (1) {
        //获取原视频的 音轨
        AVAssetTrack *originalAudioAssetTrack = [[videoAsset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0];
        originalAudioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        [originalAudioCompositionTrack insertTimeRange:video_timeRange ofTrack:originalAudioAssetTrack atTime:kCMTimeZero error:nil];
    }
    
    //+音频资源
    AVAsset *audioAsset = [AVAsset assetWithURL:self.audioURL];
    AVAssetTrack *audioTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0];
    AVMutableCompositionTrack *bgAudioCompositonTrack = nil;
    if (audioAsset != nil) {
        bgAudioCompositonTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
//        [bgAudioCompositonTrack insertTimeRange:video_timeRange ofTrack:audioTrack atTime:kCMTimeZero error:nil];
        //timeRange 截取音频的 哪一range
        [bgAudioCompositonTrack insertTimeRange:CMTimeRangeMake(CMTimeMake(60, 1), videoAsset.duration) ofTrack:audioTrack atTime:kCMTimeZero error:nil];

    }
    
    //输出
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:composition presetName:AVAssetExportPresetHighestQuality];//presetName 否则导出失败
    NSString *outputPath = [XSFileManager tempVideoPath];
    exportSession.outputURL = [NSURL fileURLWithPath:outputPath];
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;
    exportSession.shouldOptimizeForNetworkUse = YES;
    //音量控制
    AVAudioMix *audioMix = [self buildAudioMixWithVideoTrack:originalAudioCompositionTrack VideoVolume:0.1 BGMTrack:bgAudioCompositonTrack BGMVolume:1.0 atTime:kCMTimeZero];
    exportSession.audioMix = audioMix;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        NSLog(@"status:%ld",exportSession.status);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (exportSession.status == AVAssetExportSessionStatusCompleted) {
                NSURL *outputURL = exportSession.outputURL;
                [XSPhotosManager saveToPhotoLibrary:outputURL completion:^(NSError * _Nonnull error) {
                    [self.navigationController popViewControllerAnimated:NO];

                }];
                
            }else{
                NSLog(@"merge fail:%@",exportSession.error);
            }
        });
    }];

    
}

#pragma mark - 调节合成的音量
//原音 + 新增背景音
- (AVAudioMix *)buildAudioMixWithVideoTrack:(AVCompositionTrack *)videoTrack VideoVolume:(float)videoVolume BGMTrack:(AVCompositionTrack *)BGMTrack BGMVolume:(float)BGMVolume atTime:(CMTime)volumeRange {
    //    创建音频混合类
    AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
    
    //    拿到视频声音轨道设置音量
    AVMutableAudioMixInputParameters *Videoparameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:videoTrack];
    [Videoparameters setVolume:videoVolume atTime:volumeRange];
    
    //    设置背景音乐音量
    AVMutableAudioMixInputParameters *BGMparameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:BGMTrack];
    [BGMparameters setVolume:BGMVolume atTime:volumeRange];
    
    //    加入混合数组
    audioMix.inputParameters = @[Videoparameters,BGMparameters];
    
    return audioMix;
}





- (IBAction)backAction:(id)sender {
    [super backAction:sender];
    
}

 



@end
